<template>
  <div>
    <MyTable :arr="list">
      <!-- 插槽 -->
      <template slot="header">
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <!-- 具名插槽，作用域插槽 -->
      <template #body="{ item }">
        <td>{{ item.id }}</td>
        <td>{{ item.goods_name }}</td>
        <td>{{ item.goods_price }}</td>

        <td>
          <!-- 按钮切换input，聚焦，esc清除，失焦，回车push进数组并清空，事件 -->
          <input
            type="text"
            v-if="item.inputVisible"
            @blur="item.inputVisible = false"
            @keydown.esc="item.inputValue = ''"
            @keydown.enter="enterFn(item)"
            v-focus
            v-model="item.inputValue"
            :style="{ width: '80px', height: '26px' }"
          />
          <button
            class="btn btn-primary btn-sm add-tag"
            @click="item.inputVisible = true"
            v-else
          >
            +Tag
          </button>

          <br />
          <span
            class="badge badge-warning"
            v-for="(items, index) in item.tags"
            :key="index"
          >
            <span
              :style="{ position: 'relative', cursor: 'default' }"
              @mouseenter="dis"
              @mouseleave="disr"
              class="myspan"
            >
              {{ items }}
              <i
                class="a"
                @click="Del(item.tags, index)"
                :style="{ cursor: 'pointer', display: 'none' }"
                ref="lis"
                >x</i
              >
            </span>
          </span>
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="DelBtn(item.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from './MyTable'
export default {
  components: {
    MyTable,
  },
  data() {
    return {
      list: [], // 所有数据
    }
  },
  // 生命周期获取数据
  created() {
    this.$axios({
      url: '/api/goods',
      method: 'GET',
    }).then((res) => {
      let {
        data: { data },
      } = res
      this.list = data
      console.log(this.list)
    })
  },
  methods: {
    // 删除每项按钮
    DelBtn(socp) {
      this.list = this.list.filter((item) => {
        return item.id !== socp
      })
    },
    // 删除单个标签
    Del(item, b) {
      item.splice(b, 1)
    },
    // 鼠标经过移除事件
    dis(e) {
      e.target.firstElementChild.style.display = 'block'
    },
    disr(e) {
      e.target.firstElementChild.style.display = 'none'
    },
    // 回车事件
    enterFn(item) {
      if (item.inputValue === '') return alert('内容不能为空')
      item.tags.push(item.inputValue)
      item.inputValue = ''
    },
  },
  directives: {
    focus: {
      inserted(el) {
        el.focus()
      },
    },
  },
}
</script>
<style>
.badge {
  margin: 5px 10px 0 0;
}
.myspan {
  display: inline-block;
  line-height: 20px;
  padding: 0 5px;
}
</style>
